import { getMinioSts } from '@/api/minio'
import { parseSessionToken } from '@/utils/minio'
import { defineStore } from 'pinia'
import { ref } from 'vue'

// import { devIgnore } from '@/config/dev.ignore'

export const useMinioStore = defineStore(
  'minio',
  () => {
    const defaultCredential = {
      accessKey: '',
      secretKey: '',
      sessionToken: '',
    }
    // TODO
    // if (import.meta.env.MODE === 'development') {
    //    defaultCredential = devIgnore.minioCredential
    // }

    const credential = ref(JSON.parse(JSON.stringify(defaultCredential)))
    const setCredential = (val) => {
      credential.value = val
    }
    const clearCredential = () => {
      credential.value = undefined
      credential.value = JSON.parse(JSON.stringify(defaultCredential))
    }

    async function requestCredential() {
      const { code, data } = await getMinioSts()
      if (code === 0) {
        setCredential(data)
      }
    }
    // 登录初始化 , 做凭证过期时间检查等 , 过期自动获取
    async function checkExpired() {
      if (!credential.value.sessionToken) {
        return
      }
      const { expirationDate } = parseSessionToken(credential.value.sessionToken)

      if (expirationDate < new Date()) {
        await requestCredential()
      }
    }

    return { credential, setCredential, clearCredential, checkExpired }
  },
  {
    persist: true,
  },
)
